import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stores_requisition_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/odoo/stores_requisition.dart';
import 'package:flutter_admin/models/odoo/stores_requisition_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_quantity.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:quiver/strings.dart';

class StoresRequisitionDetail extends StatefulWidget {
  StoresRequisition? storesRequisition;
  StoresRequisitionDetail({required this.storesRequisition, Key? key})
      : super(key: key);
  @override
  _StoresRequisitionDetailState createState() =>
      _StoresRequisitionDetailState();
}

class _StoresRequisitionDetailState extends State<StoresRequisitionDetail> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);
  StoresRequisitionInfo storesRequisitionInfo = StoresRequisitionInfo();
  List<StoresRequisitionInfo> selectedList = [];
  List<SelectOptionVO> locationIdList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    storesRequisitionInfo.parentId = widget.storesRequisition!.id; // 查询条件
    // storesRequisitionInfo.number = widget.storesRequisition!.number;
    // storesRequisitionInfo.purpose = widget.storesRequisition!.purpose;
    // // storesRequisitionInfo.locationName = widget.storesRequisition!.workshopName;
    // storesRequisitionInfo.userName = widget.storesRequisition!.userName;
    // storesRequisitionInfo.requisitionDate =
    //     widget.storesRequisition!.requisitionDate;
    setState(() {});
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 200,
            enable: false,
            label: '领料单号',
            value: widget.storesRequisition!.number,
          ),
          CryInput(
            width: 160,
            enable: false,
            label: '用途',
            value: widget.storesRequisition!.purpose,
          ),
          CryInput(
            width: 160,
            enable: false,
            label: '车间',
            value: widget.storesRequisition!.workshopName,
          ),
          CryInput(
            width: 160,
            enable: false,
            label: '领料人',
            value: widget.storesRequisition!.userName,
          ),
          CryInput(
            width: 160,
            enable: false,
            label: '领料时间',
            value: widget.storesRequisition!.requisitionDate,
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('物料编码'),
        ),
        DataColumn(
          label: Text('物料名称'),
        ),
        DataColumn(
          label: Text('规格型号'),
        ),
        DataColumn(
          label: Text('数量'),
        ),
        DataColumn(
          label: Text('单位'),
        ),
      ],
      getCells: (m) {
        StoresRequisitionInfo storesRequisitionInfo =
            StoresRequisitionInfo.fromMapDetail(m);
        return [
          DataCell(Text(storesRequisitionInfo.productCode ?? '--')),
          DataCell(Text(storesRequisitionInfo.productName ?? '--')),
          DataCell(Text(storesRequisitionInfo.productDes ?? '--')),
          DataCell(Text(storesRequisitionInfo.quantity != null
              ? storesRequisitionInfo.quantity.toString()
              : '--')),
          DataCell(Text(storesRequisitionInfo.productUomName ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(children: <Widget>[
      CryButton(
        label: "导出",
        onPressed: () => _generateExcel(),
        iconData: Icons.import_export_outlined,
      ),
    ]);
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            // final ScaffoldState? scaffold = Scaffold.maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('领料单明细'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  Future<dynamic> findAll() async {
    formKey.currentState?.save();
    List<StoresRequisitionInfo> resultList = [];
    ResponseBodyApi responseBodyApi = await StoresRequisitionOdooApi.findAll(data: {
      "domainList": storesRequisitionInfo.toDetailDomainList(),
    });
    if (responseBodyApi.success!) {
      resultList = responseBodyApi.data
          .map<StoresRequisitionInfo>(
              (e) => StoresRequisitionInfo.fromMapDetail(e,storesRequisition: widget.storesRequisition))
          .toList();
    }
    return resultList;
  }

  _generateExcel() async {
    List<StoresRequisitionInfo> selectedList = await findAll();
    if (selectedList == null) {
      return;
    }
    List<Map> map = [
      {
        'name': 'number',
        'label': '领料单号',
        'columnWidth': 15.0,
      },
      {
      'name': 'purpose',
      'label': '用途',
      'columnWidth': 10.0,
      },
      {
      'name': 'workshopName',
      'label': '车间',
      'columnWidth': 19.0,
      },
      {
      'name': 'userName',
      'label': '领料人',
      'columnWidth': 10.0,
      },
      {
      'name': 'requisitionDate',
      'label': '领料时间',
      'columnWidth': 12.0,
      },
      {
        'name': 'productCode',
        'label': '物料编码',
        'columnWidth': 10.0,
      },
      {
        'name': 'productName',
        'label': '物料名称',
        'columnWidth': 14.0,
      },
      {
        'name': 'productDes',
        'label': '规格型号',
        'columnWidth': 14.0,
      },
      {
        'name': 'quantity',
        'label': '数量',
        'columnWidth': 10.0,
      },
      {
        'name': 'productUomName',
        'label': '单位',
        'columnWidth': 10.0,
      },
    ];
    Utils.generateExcel(fileName: "领料单明细", configure: map, data: selectedList);
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StoresRequisitionOdooApi.pageDetail(
        data: {
          "page": page,
          "domainList": storesRequisitionInfo.toDetailDomainList()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StoresRequisitionInfo>(
                (e) => StoresRequisitionInfo.fromMapDetail(e))
            .toList() ??
        [];
    setState(() {});
  }
}
